using Crux.Core.Payloads;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Crux.Core.Mvc.Filters;
/// <summary>
/// ModelValidationFilter
/// </summary>
public class ModelValidationFilter(ILogger<ModelValidationFilter> logger) : IAsyncActionFilter
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        if (context.ModelState.IsValid)
        {
            await next().ConfigureAwait(false);
        }
        else
        {
            context.Result = new BadRequestObjectResult(Payload.Error("ModelValidateError"));

            var request = context.HttpContext.Request;

            logger.LogDebug($"model is unvalid,method:{request.Method},url:{request.Path}");
        }
    }
}